package com.hspedu.reflection;

import com.hspedu.Cat;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 谷其昊
 * @version 1.0
 * @date 2022/3/22
 * @time 12:04
 */
public class Reflection02 {

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        m1();
        m2();
        m3();
    }

    /**
     * 猜测是使用传统方法调用hi的效率
     */
    public static void m1(){
        Cat cat = new Cat();
        Long start = System.currentTimeMillis();
        for (int i = 0; i < 9000000; i++) {
            cat.hi();
        }
        Long end = System.currentTimeMillis();
        System.out.println("m1耗时"+(end - start));
    }

    /**
     * 测试使用反射机制调用hi的效率
     */
    public static void m2() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        Class aClass = Class.forName("com.hspedu.Cat");
        Object cat = aClass.newInstance();
        Method method = aClass.getMethod("hi");
        Long start = System.currentTimeMillis();
        for (int i = 0; i < 9000000; i++) {
            method.invoke(cat);
        }
        Long end = System.currentTimeMillis();
        System.out.println("m2耗时"+(end - start));
    }

    /**
     * 测试优化后使用反射机制调用hi的效率
     */
    public static void m3() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        Class aClass = Class.forName("com.hspedu.Cat");
        Object cat = aClass.newInstance();
        Method method = aClass.getMethod("hi");
        method.setAccessible(true);
        Long start = System.currentTimeMillis();
        for (int i = 0; i < 9000000; i++) {
            method.invoke(cat);
        }
        Long end = System.currentTimeMillis();
        System.out.println("m3耗时"+(end - start));
    }
}
